package com.meilai.project.service.administration.goods.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meilai.project.dto.administration.goods.GoodsManageDTO;
import com.meilai.project.entity.administration.goods.Goods;
import com.meilai.project.exception.CommonException;
import com.meilai.project.mapper.administration.goods.GoodsManageMapper;
import com.meilai.project.service.administration.goods.GoodsManageService;
import com.meilai.project.vo.administration.goods.GoodsManageVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ykb
 * @date 2022/2/12 20:19
 */
@Service
@Log4j2
public class GoodsManageServiceImpl extends ServiceImpl<GoodsManageMapper, Goods> implements GoodsManageService {


    @Override
    public Page<GoodsManageVO> selectPageList(Integer current_page, Integer page_size, GoodsManageDTO searchDTO) {
        Page<GoodsManageVO> page = new Page<>(current_page, page_size);
        List<GoodsManageVO> list = baseMapper.selectPageList(page, searchDTO);

        return page.setRecords(list);
    }

    @Override
    public List<GoodsManageVO> selectList(GoodsManageDTO searchDTO) {
        return baseMapper.selectPageList(searchDTO);
    }


    @Override
    @Transactional
    public Boolean addOne(GoodsManageDTO dto) {
        List<Goods> list = list(new QueryWrapper<Goods>().isNull("deleted_at").eq("supplier_id",dto.getSupplier_id()).eq("name", dto.getName()));
        if (list != null && list.size() > 0) throw new CommonException("该物品名称已存在");
        Goods goods = new Goods();
        BeanUtils.copyProperties(dto, goods);

        return save(goods);
    }


    @Override
    @Transactional
    public Boolean editOne(GoodsManageDTO dto) {
        Goods temp = getById(dto.getId());
        if (temp == null) return false;
        Goods goods = new Goods();
        BeanUtils.copyProperties(dto, goods);
        return updateById(goods);
    }


    @Override
    @Transactional
    public Boolean delete(Long id) {
        LocalDateTime now = LocalDateTime.now();
        Goods temp = getById(id);
        if (temp == null) return false;
        Goods goods = new Goods();
        goods.setId(id);
        goods.setDeleted_at(now);
        return updateById(goods);
    }

}
